package org.onionframework.faces.extension;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.faces.view.facelets.ResourceResolver;

import org.onionframework.servlet.ServletContexts;

import com.sun.faces.facelets.impl.DefaultResourceResolver;

/**
 * 模板位置解析器，在父类正常的查找模板路径失败后，在类路径中
 * 再次查找，于是可以将页面.xhtml打到jar中
 * 
 * 注意：
 * 	1.本类只处理.xhtml的模板，对于静态资源，使用com.ai.core.jsf.web.filter.ResoureceFilter处理
 * 	2.因为先找正常路径，所以可以使用覆盖的方法扩展、改变jar中的xhtml，例如在webapp目录下放一个/security/login.xhtml
 * 	就会覆盖authentication项目中默认的登陆页面
 * 
 * @author allan
 *
 */
public class TemplateResolver extends DefaultResourceResolver {

	private ResourceResolver defaultResourceResolver;

	/**
	 * @param resourceHandler
	 */
	public TemplateResolver(ResourceResolver resourceResolver) {
		super(null);
		this.defaultResourceResolver = resourceResolver;
	}

	private Logger log = Logger.getLogger(getClass().getName());
	private static List<String> viewPaths = new ArrayList<String>();
	private static boolean useSrcPaths = false;
	
	/*static{
		ServletContext context = ServletContexts.getServletContext();
		if("true".equals(context.getInitParameter("facelets.DEVELOPMENT"))){
			useSrcPaths = true;
			try {
				initSrcPaths();
			} catch (Exception e) {
				throw new SystemException(e);
			}
		}
	}*/
	
	/*public static void initSrcPaths() throws URISyntaxException, IOException{
		String path = TemplateResolver.class.getResource("/").toURI().getPath();
		String project = path + "../../../../../";
		
		File file = new File(project);
		
		if(file.getCanonicalPath().endsWith("shell")){
			project = project + "../";	
		}
		
		file = new File(project + "pom.xml");
		
		if(!file.exists())
			return;
		
		String content = FileUtils.readFileToString(file);
		
		if(content.indexOf("<modules>") == -1){
			path = project + "src/main/resources/META-INF/resources";
			file = new File(path);
			if(file.exists())
				viewPaths.add(path);
			
			path = project + "src/test/resources/META-INF/resources";
			file = new File(path);
			if(file.exists())
				viewPaths.add(path);
		}else{
			
			Pattern pattern = Pattern.compile("\\<module\\>[^\\<]*\\<\\/module\\>");
			Matcher matcher = pattern.matcher(content);
			String group;
			
			while(matcher.find()){
				group = matcher.group();
				group = group.substring(group.indexOf(">") + 1,group.indexOf("</"));
				path = project + group + "/src/main/resources/META-INF/resources";
				
				file = new File(path);
				if(file.exists())
					viewPaths.add(file.getCanonicalPath());
				
				path = project + group + "/src/test/resources/META-INF/resources";
				
				file = new File(path);
				if(file.exists())
					viewPaths.add(file.getCanonicalPath());			
			}
		}
	}*/
	
    /** first check the context root, then the classpath */
	@Override
    public URL resolveUrl(String path) {
		URL url = null;
		try {
			url = ServletContexts.getServletContext().getResource(path);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		if(url == null){
			log.fine("Resolving URL " + path);
        
        	/*if(useSrcPaths){
	        	File file;
	        	for(String parent : viewPaths){
	        		try {
	        			file = new File(parent + path);
						if(file.exists())
	        				return file.getCanonicalFile().toURI().toURL();				
					} catch (Exception e) {
						throw new SystemException(e);
					}
	        	}
        	}
        	*/
            /* classpath resources don't start with / */
			
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            
            path = "META-INF/resources/" + path;
            
            url = Thread.currentThread().getContextClassLoader().
                    getResource(path);
		}
        return url;
    }
}
